// src/components/OnlineCollecting/ArchiveTypeTree.tsx
import React, { useState, useEffect, useCallback } from 'react';
import { Tree, Card, Button, Space, Tooltip, message } from 'antd';
import { FolderOutlined, UpOutlined, DownOutlined, ReloadOutlined } from '@ant-design/icons';
import { queryArchiveTypes } from '@/services/prefiling/onlineCollecting';
import { buildTreeData } from '@/utils/tree';
import { ArchiveType } from '@/types/prefiling/onlineCollecting';
import styles from './ArchiveTypeTree.less';

const { DirectoryTree } = Tree;

interface ArchiveTypeTreeProps {
  menuId: string;
  onSelect: (typeNode: ArchiveType) => void;
}

const ArchiveTypeTree: React.FC<ArchiveTypeTreeProps> = ({ menuId, onSelect }) => {
  const [expanded, setExpanded] = useState(true); // Controls expand/collapse state
  const [loading, setLoading] = useState(false);
  const [treeData, setTreeData] = useState<ArchiveType[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);

  const treeConfig = {
    checkable: false,
    selectable: true,
    showLine: true,
    showIcon:false
  };

  const handleTreeSelect = (selectedKeys: React.Key[], info: any) => {
    const node = info.node as ArchiveType;
    if (node.children) {
      let txt = "只能选择末级节点";
      if (!node.typeCode) {
        txt = "当前节点为全宗节点";
      }
      if (node.type == "0") {
        txt = "当前节点为分组";
      }
      message.warning(txt);
    } else {
      setSelectedKeys(selectedKeys);
      onSelect(node);
    }
  };

  const handleExpand = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    
    const newExpanded = !expanded;
    setExpanded(newExpanded);
    
    if (newExpanded && treeData.length > 0) {
      setExpandedKeys(treeData.map(node => node.key || node.id));
    } else {
      setExpandedKeys([]);
    }
  };
  

  const handleRefresh = () => {
    loadTreeData();
  };

  const findFirstDeepestLeafWithPath = useCallback((nodes: ArchiveType[]): {
    node: ArchiveType | null;
    path: React.Key[];
  } => {
    if (!nodes || nodes.length === 0) return { node: null, path: [] };
    
    let current = nodes[0];
    const path: React.Key[] = [current.id];
    
    while (current.children && current.children.length > 0) {
      current = current.children[0];
      path.push(current.id);
    }
    
    return { node: current, path: path.slice(0, -1) }; // Exclude leaf node itself from expansion
  }, []);

  const loadTreeData = async (): Promise<void> => {
    try {
      setLoading(true);
      const response = await queryArchiveTypes({ menuId });
      const tree = buildTreeData(response, 'id', 'name', 'pId');
      // 确保每个节点都有 key
      const processNode = (node: ArchiveType) => {
        node.key = node.id;
        if (node.children) {
          node.children.forEach(processNode);
        }
      };
      tree.forEach(processNode);
      
      setTreeData(tree);
      const { node: firstLeaf, path } = findFirstDeepestLeafWithPath(tree);
      setExpandedKeys(path);
  
      if (firstLeaf) {
        setSelectedKeys([firstLeaf.id]);
        onSelect(firstLeaf);
      }
    } catch (error) {
      console.error('error', error);
    } finally {
      setLoading(false);
    }
  };
//   const loadTreeData = async (): Promise<void> => {
//     try {
//       setLoading(true);
//       const response = await queryArchiveTypes({ menuId });
//       const tree = buildTreeData(response, 'id', 'name', 'pId');
//       console.log(tree)
//       setTreeData(tree);
//       const { node: firstLeaf, path } = findFirstDeepestLeafWithPath(tree);
//       setExpandedKeys(path);

//       console.log(firstLeaf)
//       if (firstLeaf) {
//         setSelectedKeys([firstLeaf.id]);
//         onSelect(firstLeaf);
//       }
//     } catch (error) {
//       console.error('error', error);
//     } finally {
//       setLoading(false);
//     }
//   };

  useEffect(() => {
    loadTreeData();
  }, [menuId]);

  return (
    <Card
      title={
        <div>
          <FolderOutlined /> 档案类型
        </div>
      }
      extra={
        <Space>
          <Tooltip title={expanded ? '折叠' : '展开'}>
            <Button
              type="text"
              icon={expanded ? <UpOutlined /> : <DownOutlined />}
              onClick={handleExpand}
            />
          </Tooltip>
          <Tooltip title="刷新">
            <Button type="text" icon={<ReloadOutlined />} onClick={handleRefresh} />
          </Tooltip>
        </Space>
      }
      className={styles.treeCard}
    >
      <DirectoryTree
        treeData={treeData}
        onSelect={handleTreeSelect}
        {...treeConfig}
        expandedKeys={expandedKeys}
        selectedKeys={selectedKeys}
        onExpand={(keys) => setExpandedKeys(keys)}  // 确保同步状态
        className={styles.tree}
      />
    </Card>
  );
};

export default ArchiveTypeTree;